import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from "@angular/common/http";
import { ApiConfigService } from "./api-config.service";

@Injectable({
  providedIn: 'root'
})
export class HttpCustomService {
  constructor(private http: HttpClient) { }

  /**
   * @param api 接口地址
   * @param params 参数实体
   */
  get(api, params) {
    let url = ApiConfigService.appApiUrl + api;
    let paramsStr = "";
    for (let key in params) {
      if (params.hasOwnProperty(key)) {
        let value = params[key];
        paramsStr += key + "=" + value + "&";
      }
    }
    if (paramsStr.length > 0) {
      url = url + "?" + paramsStr.substring(0, paramsStr.length - 1);
    }
    let options = {
      headers: new HttpHeaders({
        Authorization: ApiConfigService.token
      })
    };
    return this.http
      .get(url, options)
      .toPromise()
      .then((data) => {
        return data;
      })
      .catch((err) => {
        return err;
      });
  }


  /**
   * @param api 接口地址
   * @param body 实体内容
   */
  post(api, body) {
    let url = ApiConfigService.appApiUrl + api;
    let options = {
      headers: new HttpHeaders({
        Authorization: ApiConfigService.token
      })
    };
    return this.http
      .post(url, body, options)
      .toPromise()
      .then((data) => {
        return data;
      })
      .catch((err) => {
        return err;
      });
  }
}
